//
//  CustomSwitchView.m
//  AmountBody
//
//  Created by Qiu Jishuai on 2017/12/30.
//  Copyright © 2017年 RCMTM. All rights reserved.
//

#import "CustomSwitchView.h"
#import "UIColor+Extension.h"
#import "UIView+Extension.h"
#import <ReactiveObjC/ReactiveObjC.h>

static const CGFloat buttonW = 62;
static const CGFloat margin = 16;

@interface CustomSwitchView()
@property (nonatomic, strong) NSMutableArray<UIButton *> *buttons;
@property (nonatomic, strong) NSMutableArray<UIImageView *> *imageViews;
@property (nonatomic, strong) UIButton *lastButton;
@end

@implementation CustomSwitchView

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
         [self setupViews];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
         [self setupViews];
    }
    return self;
}

#pragma mark - Public Method
- (void)setEnabled: (BOOL)isEnabled index: (NSInteger)index {
    if (index > (NSInteger)self.buttons.count - 1) {
        return;
    }
    if (isEnabled == self.buttons[index].isEnabled) {
        return;
    }
    self.buttons[index].enabled = isEnabled;
    if (index < 4) {
        self.imageViews[index].image = isEnabled ? self.normalImage : self.disabledImage;
    }
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    if (selectedIndex > (NSInteger)self.buttons.count - 1) {
        return;
    }
    if (selectedIndex == [self.buttons indexOfObject:self.lastButton]) {
        return;
    }
    _selectedIndex = selectedIndex;
    self.lastButton.selected = NO;
    self.lastButton = self.buttons[selectedIndex];
    self.lastButton.selected = YES;
    if (!_lastButton.isEnabled) {
        _lastButton.enabled = YES;
        if (selectedIndex < 4) {
            self.imageViews[selectedIndex].image = self.normalImage;
        }
    }
}

#pragma mark - Private Method
- (void)setupViews {

    NSArray *imageNames = @[@"custom_switch_btn_style",
                            @"custom_switch_btn_design",
                            @"custom_switch_btn_design_all",
                            @"custom_switch_btn_measure",
                            @"custom_switch_btn_order"];

    NSArray *normalImages = [imageNames map:^UIImage *(NSString *name) {
        return [UIImage imageNamed:name];
    }];

    NSArray *disabledImages = [imageNames map:^UIImage *(NSString *name) {
        return [UIImage imageNamed:[name stringByAppendingString:@"_disabled"]];
    }];

    NSArray *selectedImages = [imageNames map:^UIImage *(NSString *name) {
        return [UIImage imageNamed:[name stringByAppendingString:@"_selected"]];
    }];

    [normalImages enumerateObjectsUsingBlock:^(UIImage * image, NSUInteger idx, BOOL * stop) {
        UIButton *button = [[UIButton alloc] init];
        button.imageView.contentMode = UIViewContentModeCenter;
        button.imageView.clipsToBounds = NO;
        UIImage *bgImage = [[UIImage imageNamed:@"custom_switch_btn_bg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [button setBackgroundImage:bgImage forState:UIControlStateNormal];
        button.enabled = NO;
        [button setImage:normalImages[idx] forState:UIControlStateNormal];
        [button setImage:disabledImages[idx] forState:UIControlStateDisabled];
        [button setImage:selectedImages[idx] forState:UIControlStateSelected];
        button.tag = idx;
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

        [self.buttons addObject:button];
        [self addSubview:button];

        if (idx == 3) {//第三个略偏
            button.imageEdgeInsets = UIEdgeInsetsMake(-2, 0, 2, 0);
        }

        if (idx < 4) {
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.image = [self disabledImage];
            imageView.contentMode = UIViewContentModeCenter;
            [self addSubview:imageView];
            [self.imageViews addObject:imageView];
        }
    
        [RACObserve(button, selected) subscribeNext:^(NSNumber *x) {
            BOOL isSelected = x.boolValue;
            CGFloat scale = isSelected ? 1.2 :1.0;
            [button.imageView startScaleAnimationWithScaleX:scale scaleY:scale completionBlock:nil];
        }];
    }];
}

- (UIImage *)normalImage {
    return [UIImage imageNamed:@"custom_switch_margin"];
}

- (UIImage *)disabledImage {
    return [UIImage imageNamed:@"custom_switch_margin_disabled"];
}


- (void)layoutSubviews {
    [super layoutSubviews];

    if (self.buttons.firstObject.frame.size.height == buttonW) {
        return;
    }

    [self.buttons enumerateObjectsUsingBlock:^(UIButton * button, NSUInteger idx, BOOL * stop) {
        CGFloat y = idx * (buttonW + margin);
        button.frame = CGRectMake(0, y, buttonW, buttonW);
        if (idx < 4) {
            self.imageViews[idx].frame = CGRectMake(0, CGRectGetMaxY(button.frame), buttonW, margin);
        }
    }];
}

#pragma mark - Event Response
- (void)buttonClicked: (UIButton *)sender {
    if (sender.isSelected) {
        return;
    }
    NSInteger lastIndex = self.lastButton.tag;
    self.lastButton.selected = NO;
    self.lastButton = sender;
    self.lastButton.selected = YES;

    if (self.switchBlock) {
        self.switchBlock(lastIndex, sender.tag);
    }
}

#pragma mark - Getter
- (NSMutableArray *)buttons {
    if (!_buttons) {
        _buttons = [NSMutableArray arrayWithCapacity:5];
    }
    return _buttons;
}

- (NSMutableArray<UIImageView *> *)imageViews {
    if (!_imageViews) {
        _imageViews = [NSMutableArray arrayWithCapacity:4];
    }
    return _imageViews;
}

@end
